import { defineStore } from 'pinia'
import axios from 'axios'

export interface ChatInfo {
  id: number
  name: string
  type: 'friends' | 'group'
  initials: string
  lastMessage: string
  unread: number
  messages: { id: number; content: string; self: boolean }[]
}

export const useChatStore = defineStore('chat', {
  state: () => ({
    chatList: [] as ChatInfo[],
    selectedChat: null as ChatInfo | null,
  }),

  actions: {
    async fetchFriends() {
      try {
        const token = localStorage.getItem('jwt_token') || ''
        const res = await axios.get('http://localhost:8080/api/friends/getFriend', {
          headers: {
            Authorization: `Bearer ${token}`,
          }
        })

        // 后端返回格式：[{userId, username}, ...]
        return res.data
      } catch (error) {
        console.error('获取好友列表失败', error)
        return []
      }
    },

    async fetchGroups(userId: number) {
      try {
        const res = await axios.get(`http://localhost:8080/api/chatroom/joined/${userId}`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('jwt_token') || ''}`,
          },
        })

        // 返回UserJoinedRoomDTO数组
        return res.data
      } catch (error) {
        console.error('获取群组列表失败', error)
        return []
      }
    },

    async loadChatList() {
      const userIdStr = localStorage.getItem('user_id')
      if (!userIdStr) return

      const userId = Number(userIdStr)
      const [friends, groups] = await Promise.all([this.fetchFriends(), this.fetchGroups(userId)])

      // 组装成ChatInfo格式
      const friendChats: ChatInfo[] = friends.map((f: any) => ({
        id: f.userId,
        name: f.username,
        type: 'friends',
        initials: this.getInitials(f.username),
        lastMessage: '',
        unread: 0,
        messages: [],
      }))

      const groupChats: ChatInfo[] = groups.map((g: any) => ({
        id: g.roomId,
        name: g.roomName,
        type: 'group',
        initials: this.getInitials(g.roomName),
        lastMessage: '',
        unread: 0,
        messages: [],
      }))

      this.chatList = [...friendChats, ...groupChats]

      // 默认选中第一个聊天
      if (this.chatList.length > 0) this.selectedChat = this.chatList[0]
    },

    getInitials(name: string): string {
      if (!name) return ''
      const words = name.trim().split(' ')
      if (words.length === 1) return words[0][0].toUpperCase()
      return words[0][0].toUpperCase() + words[1][0].toUpperCase()
    },

    selectChat(chat: ChatInfo) {
      this.selectedChat = chat
    },

    sendMessage(content: string) {
      if (!this.selectedChat) return
      this.selectedChat.messages.push({
        id: Date.now(),
        content,
        self: true,
      })
      this.selectedChat.lastMessage = content
      this.selectedChat.unread = 0
    },
  },
})
